<template>
  <div>
    <el-row>
      <el-col
        ><el-button type="primary" @click="addAdmin">新增</el-button></el-col
      >
      <el-col style="margin-top: 10px">
        <el-table
          class="box-table"
          :data="Data"
          :stripe="true"
          :border="true"
          :fit="true"
          v-if="Data != null"
        >
          <el-table-column
            prop="id"
            label="ID"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="name"
            label="管理员名称"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="account"
            label="账号"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="createtime"
            label="创建时间"
            width="auto"
            align="center"
            header-align="center"
          >
            <template #default="scope">
              {{ scope.row.createtime.split("T")[0] }}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="auto"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="editAdmin(scope.row)"
                >编辑</el-button
              >
              <el-button
                link
                type="primary"
                size="small"
                @click="delBerbak(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col style="margin: 0 auto">
        <el-card>
          <div class="block">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              :total="Total"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-col>

      <el-dialog
        :title="title"
        v-model="dialogFormVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-form :model="form" label-position="right">
          <el-form-item label="管理员名称:" label-width="120px">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="角色:" label-width="120px">
            <el-cascader
              v-model="form.role"
              :options="options"
              clearable
              @change="change1"
            />
          </el-form-item>
          <el-form-item
            v-if="form.role == '1'"
            label="所属区县:"
            label-width="120px"
          >
            <el-cascader
              v-model="form.district"
              :options="options2"
              clearable
              @change="change2"
            />
          </el-form-item>
          <el-form-item
            v-if="form.role == '2'"
            label="所属VCT门诊:"
            label-width="120px"
          >
            <el-checkbox-group v-model="form.outpatientId" @change="change">
              <el-checkbox
                v-for="(item, index) in options3"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-checkbox-group>
            <!-- <el-select
              v-model="form.outpatientId"
              size="large"
              style="width: 240px"
            >
              <el-option
                v-for="item in options3"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select> -->
          </el-form-item>
          <el-form-item label="账号:" label-width="120px">
            <el-input
              v-if="title == '新增管理员'"
              placeholder="请输入 6 到 12 位字符"
              maxlength="12"
              minlength="6"
              show-word-limit
              v-model="form.account"
            ></el-input>
            <el-input
              v-if="title == '编辑管理员'"
              placeholder="请输入 6 到 12 位字符"
              maxlength="12"
              minlength="6"
              show-word-limit
              disabled
              v-model="form.account"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="show" label="密码:" label-width="120px">
            <el-input
              placeholder="请输入 6 到 12 位字符"
              maxlength="12"
              minlength="6"
              show-word-limit
              v-model="form.password"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              v-if="title == '编辑管理员' && !show"
              type="primary"
              @click="show = true"
              >修改密码</el-button
            >
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="margin-top: 10px">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </div>
      </el-dialog>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRaw, onMounted, onBeforeMount } from "vue";
import apiService from "@/services/apiService";
import { v4 as uuidv4 } from "uuid";
import { Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoleStore } from "@/store/modules/useRoleStore";
import { storeToRefs } from "pinia";

defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "Admin"
});
const roleStore = useRoleStore();
const { role } = storeToRefs(roleStore);
//表格数据
const Data = ref<any>([]);
const checkList = ref<any>([]);
const currentPage = ref(1); // 当前页数
const pageSize = ref(100); // 每页条数
const Total = ref<number>(1); //总条数
const title = ref("新增管理员");
const show = ref(true);
const id = ref(1);
const options = [
  {
    value: "1",
    label: "区级管理员"
  },
  {
    value: "2",
    label: "VCT工作人员"
  }
];
const options2 = [
  {
    value: "",
    label: "绵阳市"
  },
  {
    value: "涪城区",
    label: "涪城区"
  },
  {
    value: "游仙区",
    label: "游仙区"
  },
  {
    value: "安州区",
    label: "安州区"
  },
  {
    value: "三台县",
    label: "三台县"
  },
  {
    value: "盐亭县",
    label: "盐亭县"
  },
  {
    value: "梓潼县",
    label: "梓潼县"
  },
  {
    value: "北川羌族自治县",
    label: "北川羌族自治县"
  },
  {
    value: "平武县",
    label: "平武县"
  },
  {
    value: "江油市",
    label: "江油市"
  }
];
const options3 = ref<any>([]);
const GetList = () => {
  const params = {
    msgid: "PagingFindAdmins",
    token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
    seq: uuidv4(),
    body: {
      pageno: currentPage.value,
      pagesize: pageSize.value
    }
  };

  apiService
    .post("", params)
    .then((res: any) => {
      // 使用 any 类型断言
      console.log(res.data);
      let arr = res.data.body.admins;
      Data.value = arr;
      Total.value = res.data.body.admins.length;
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
};
const change = event => {
  console.log(event);
  form.outpatientId = event;
};
const change1 = event => {
  console.log(event[0]);
  if (event[0] == 2) {
  }
};
const change2 = event => {
  console.log(event);
};
const GetVCTList = () => {
  const params = {
    msgid: "PagingFindVTCOutpatient",
    token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
    seq: uuidv4(),
    body: {
      pageno: currentPage.value,
      pagesize: pageSize.value,
      name: "",
      type: 1
    }
  };

  apiService
    .post("", params)
    .then((res: any) => {
      console.log(res.data);
      res.data.body.outpatients.forEach(item => {
        options3.value.push({
          value: item.id,
          label: item.name
        });
      });

      console.log(options3.value);
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
};
// 监听页码变化
const handleCurrentChange = val => {
  currentPage.value = val;
  GetList();
};

// 监听每页条数变化
const handleSizeChange = val => {
  pageSize.value = val;
  GetList();
};

//删除
const delBerbak = (row: any) => {
  ElMessageBox.confirm("确认删除?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      const params = {
        msgid: "DeleteAdmin",
        token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
        seq: uuidv4(),
        body: {
          adminid: row.id
        }
      };
      apiService.post("", params).then((res: any) => {
        console.log(res);
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "删除成功"
          });
          GetList();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};
// 新增
const form = reactive({
  name: "",
  role: "",
  account: "",
  password: "",
  superiorsadminid: 1,
  district: "",
  outpatientId: []
});

const dialogFormVisible = ref(false);
const addAdmin = () => {
  form.name = "";
  form.role = "";
  form.account = "";
  form.password = "";
  form.district = "";
  form.outpatientId = [];
  dialogFormVisible.value = true;
  title.value = "新增管理员";
};
const editAdmin = row => {
  console.log(row);
  dialogFormVisible.value = true;
  title.value = "编辑管理员";
  id.value = row.id;
  form.name = row.name;
  form.role = row.role;
  form.account = row.account;
  form.password = row.password;
  form.superiorsadminid = 1;
  form.district = row.district;
  form.outpatientId = row.outpatientId;
};

const submit = () => {
  if (title.value == "新增管理员") {
    if (form.district) {
      form.district = form?.district[0];
    }
    form.role = form.role[0];
    const params = {
      msgid: "InsertAdmin",
      token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
      seq: uuidv4(),
      body: form
    };

    apiService
      .post("", params)
      .then((res: any) => {
        console.log(res);
        if (res.data.code == 200) {
          dialogFormVisible.value = false;
          ElMessage({
            type: "success",
            message: "新增成功"
          });
          GetList();
        }
      })
      .catch(error => {
        console.error("Error fetching data:", error);
      });
  } else {
    if (form.district) {
      form.district = form?.district[0];
    }
    const params = {
      msgid: "UpdateAdminInfo",
      token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
      seq: uuidv4(),
      body: {
        id: id.value,
        name: form.name,
        role: form.role,
        account: form.account,
        password: form.password ? form.password : "",
        superiorsadminid: 1,
        district: form.district,
        outpatientId: form.outpatientId
      }
    };

    apiService
      .post("", params)
      .then((res: any) => {
        console.log(res);
        if (res.data.code == 200) {
          dialogFormVisible.value = false;
          ElMessage({
            type: "success",
            message: "编辑成功"
          });
          GetList();
        }
      })
      .catch(error => {
        console.error("Error fetching data:", error);
      });
  }
};
const cancel = () => {
  dialogFormVisible.value = false;
  form.name = "";
  form.role = "";
  form.account = "";
  form.password = "";
  form.district = "";
};
//关闭弹窗
const handleClose = (done: () => void) => {
  form.name = "";
  form.role = "";
  form.account = "";
  form.password = "";
  form.district = "";
  done();
};

onMounted(() => {
  GetList();
  GetVCTList();
});
</script>

<style lang="scss" scoped>
.active-button {
  background-color: #409eff; /* 设置按钮激活时的背景颜色 */
  color: white; /* 设置按钮激活时的文字颜色 */
}
</style>
